package sourceagile.server.subversionFileRepository;

import java.util.Collection;
import java.util.Iterator;

import org.codehaus.jettison.json.JSONArray;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.io.SVNRepository;

import sourceagile.server.utilities.ConvertFileToJson;

/**
 * List all the files from the Subversion Repository
 * 
 * @Feature
 */
public class ListSubversionFiles {

	public static String FILE_PATH = "filePath";

	public static String FILE_NAME = "fileName";

	public static String DATE_MODIFIED = "dateModified";

	public static String FILE_AUTHOR = "fileAuthor";

	public static JSONArray listEntries(String repositoryURL, String username,
			String password) {

		JSONArray entries = new JSONArray();

		SVNRepository repository;
		try {

			repository = SubversionRepositoryConnection.connect(repositoryURL,
					username, password);

			listFilesFromFolder(repository, "", entries);

		} catch (SVNException e) {

			e.printStackTrace();

		}

		return entries;
	}

	private static void listFilesFromFolder(SVNRepository repository,
			String folder, JSONArray entries) throws SVNException {

		Collection subversionEntries = repository.getDir(folder, -1, null,
				(Collection) null);

		Iterator iterator = subversionEntries.iterator();

		while (iterator.hasNext()) {

			SVNDirEntry subversionEntry = (SVNDirEntry) iterator.next();

			if (subversionEntry.getKind() != SVNNodeKind.FILE) {

				listFilesFromFolder(repository,
						getFolderPath(folder, subversionEntry), entries);

			} else {

				entries.put(ConvertFileToJson.convertFromSubversion(
						subversionEntry, folder));
			}
		}
	}

	public static String getFolderPath(String path, SVNDirEntry subversionEntry) {

		String folderPath = (path.equals("")) ? subversionEntry.getName()
				: path + "/" + subversionEntry.getName();

		return folderPath;
	}

}
